package com.efounder.org;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.baseadapter.listview.MultiItemTypeAdapter;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.http.utils.CommonRequestManager;
import com.efounder.model.GXOrgBeanList;
import com.efounder.ospmobilelib.R;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.bean.TreeBean;
import com.zhy.tree.bean.TreeHelper;
import com.zhy.tree.bean.TreeNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;


/**
 * 组织机构 参考该类
 * Created by YQS on 2017/12/28.
 */

public class OrganizationCommonFragment extends BaseFragment implements View.OnClickListener {

    private List<TreeNode> listData;//当前页面显示的节点数据
    private List<OrgBean> topListData;//横向滑动的节点数据

    private ListView mListView;
    private SmartRefreshLayout mSrl;
    private TextView titleView;
    private EditText searchContent;
    private Button searchButton;
    private RecyclerView recyclerView;

    private OrgRecycleViewAdapter topAdapter;
    private ListAdapter1 listAdapter;
    private LinearLayoutManager layoutManager;

    private static String ORGURL = "http://11.11.48.15:8081/BSServer/org/getOrgListByParentId";
    private String orgUserId = "Y180010853";//用户id

    public OrganizationCommonFragment(StubObject stubObject) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("stubObject", stubObject);
        setArguments(bundle);

    }

    public OrganizationCommonFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_organization_common, container, false);
        initView(view);
        initAdapter();
        initData();
        return view;
    }

    private void initData() {
        StubObject stub = (StubObject) getArguments().getSerializable("stubObject");
        Hashtable hashTable = stub.getStubTable();
        String title = (String) hashTable.get("caption");
        titleView.setText(title);
        TreeNode treeNode = new TreeNode();
        treeNode.setId("");
        treeNode.setName("组织机构");
        treeNode.setAttrs(new HashMap<String,Object>());
        loadData(treeNode, true);


    }


    private void initView(View rootView) {
        mListView = (ListView) rootView.findViewById(R.id.lv_contacts);
        mSrl = (SmartRefreshLayout) rootView.findViewById(R.id.srl);
        searchContent = (EditText) rootView.findViewById(R.id.et_search);
        searchButton = (Button) rootView.findViewById(R.id.searchbut);
        searchButton.setOnClickListener(this);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycleview);
        layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        //设置增加或删除条目的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        mSrl.finishLoadMore();
        mSrl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                recyclerView.setVisibility(View.GONE);
                searchContent.setText("");
                listData.clear();
                initAdapter();
                initData();
            }
        });

        LinearLayout leftbacklayout = (LinearLayout) rootView.findViewById(R.id.leftbacklayout);
        leftbacklayout.setVisibility(View.VISIBLE);
        titleView = (TextView) rootView.findViewById(R.id.fragmenttitle);
        leftbacklayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        titleView.setTextColor(Color.WHITE);
    }


    private void initAdapter() {
        topListData = new ArrayList<>();
        topAdapter = new OrgRecycleViewAdapter(getActivity(), topListData);
        recyclerView.setAdapter(topAdapter);

        listData = new ArrayList<>();
        listAdapter = new ListAdapter1(getActivity(), listData);
        mListView.setAdapter(listAdapter);
        //item点击事件
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TreeNode node = listData.get(position - 1);
                if (node.isLeaf()) {
                    String type = (String) node.getAttrs().get("TYPE");
                    if ("USER".equals(type)) {
                        ToastUtil.showToast(getActivity(), "点击的是user");
                    } else {
                        loadData(node, true);
                    }
                } else {
                    listData.clear();
                    listData.addAll(node.getChildren());
                    addTopItem(node);

                }
                listAdapter.notifyDataSetChanged();

            }
        });

        //上方横向滑动的view的点击事件
        topAdapter.setOnRecycleViewItemClickListener(new OrgRecycleViewAdapter.OnRecycleViewItemClickListener() {
            @Override
            public void onClick(View view, OrgBean bean, int position) {
                //--移除点击的item之后的数据源start--
                List<OrgBean> tempList = new ArrayList<OrgBean>();
                for (OrgBean bean1 : topListData.subList(0, position + 1)) {
                    tempList.add(bean1);
                }
                topListData.clear();
                topListData.addAll(tempList);
                topAdapter.notifyDataSetChanged();
                //--移除点击的item之后的数据源end--

//                if (bean == null) {//点击第0个
//                    loadData(null, false);
//                } else {
                TreeNode node = bean.getTreeNode();
                listData.clear();
                listData.addAll(node.getChildren());
                listAdapter.notifyDataSetChanged();
//                }

            }


        });


    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 加载数据
     *
     * @param
     * @param parentNode 父节点
     * @param isAdd      topview是否追加
     */
    private void loadData(final TreeNode parentNode, final boolean isAdd) {
        LoadingDataUtilBlack.show(getContext());
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", orgUserId);
        if (parentNode != null) {
            Map<String, Object> attrMap = parentNode.getAttrs();
            if (attrMap.containsKey("BH")) {
                map.put("bh", (String) attrMap.get("BH"));
            }
            if (attrMap.containsKey("MX")) {
                map.put("mx", (String) attrMap.get("MX"));
            }
            if (attrMap.containsKey("JS")) {
                map.put("js", attrMap.get("JS").toString());
            }
            if (attrMap.containsKey("TYPE")) {
                map.put("type", (String) attrMap.get("TYPE"));
            }
        }
        CommonRequestManager.getInstance(getActivity()).requestAsyn(ORGURL, 0, map, new CommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                LoadingDataUtilBlack.dismiss();
                mSrl.finishLoadMore();
                mSrl.finishRefresh();

                //topview 增加item
                if (isAdd) {
                    addTopItem(parentNode);
                    recyclerView.setVisibility(View.VISIBLE);
                }

                Gson gson = new Gson();
                GXOrgBeanList list = null;
                try {
                    list = gson.fromJson(result, GXOrgBeanList.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(getActivity(), "数据错误");
                }
                if (list != null) {
                    List<TreeBean> treeBeans = parseToTreenBean(list, parentNode);
                    if (treeBeans != null && treeBeans.size() > 0) {
                        List<TreeNode> nodes = TreeHelper.convertBean2Node(treeBeans);
                        if (parentNode != null) {
                            parentNode.setChildren(nodes);
                        }
                        listData.clear();
                        listData.addAll(nodes);
                        listAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (getContext() != null) {
                    LoadingDataUtilBlack.dismiss();
                    mSrl.finishLoadMore();
                    mSrl.finishRefresh();
                    ToastUtil.showToast(getContext(), "加载失败");
                }
            }
        });
    }

    private void addTopItem(TreeNode parentNode) {

        topListData.add(new OrgBean(parentNode, true));
        topAdapter.notifyDataSetChanged();
        recyclerView.smoothScrollToPosition(topListData.size() - 1);
    }

    private List<TreeBean> parseToTreenBean(GXOrgBeanList list, TreeNode parentNode) {
        List<TreeBean> treeList = new ArrayList<>();
        for (GXOrgBeanList.DataBean bean : list.getData()) {
            String id = bean.getBH();
            String parentId = null;
            if (parentNode == null) {
                parentId = "";
            } else {
                parentId = parentNode.getId();
            }

            String name = bean.getMC();
            TreeBean treeeBean = new TreeBean(id, parentId, name);
            treeeBean.setHasCheckBox(false);
            treeeBean.setAttrs(bean.getAttrMap());
            treeList.add(treeeBean);
        }
        return treeList;
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

//    public class ListAdapter extends CommonAdapter<TreeNode> {
//
//
//        public ListAdapter(Context context, List<TreeNode> mDatas, int itemLayoutId) {
//            super(context, mDatas, itemLayoutId);
//        }
//
//        @Override
//        public void convert(ViewHolder helper, TreeNode item) {
//
//
//        }
//
//
//        public void convert(ViewHolder helper, TreeNode item, int position) {
//            super.convert(helper, item, position);
//            TextView title = helper.getView(R.id.title);
//            ImageView imageview = helper.getView(R.id.imageview);
//            ImageView rightArrowView = helper.getView(R.id.rightarrow);
//            title.setText(item.getName());
//
//        }
//    }


    public class ListAdapter1 extends MultiItemTypeAdapter<TreeNode> {
        public ListAdapter1(Context context, List<TreeNode> datas) {
            super(context, datas);
            addItemViewDelegate(new DepartmentItemDelagate());
            addItemViewDelegate(new UserItemDelagate());
        }

    }
}
